package com.bolingcavalry.crm.summaryorder.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.ResponseResult;
import com.base.Status;
import com.bolingcavalry.crm.aftersales.mapper.AfterSalesMapper;
import com.bolingcavalry.crm.message.mapper.MessageMapper;
import com.bolingcavalry.crm.minio.service.MinioService;
import com.bolingcavalry.crm.receiver.mapper.ReceiverMapper;
import com.bolingcavalry.crm.recyclebin.mapper.RecyclebinMapper;
import com.bolingcavalry.crm.recyclebin.service.OrderRestoreService;
import com.bolingcavalry.crm.security.utils.SecurityUtils;
import com.bolingcavalry.crm.serviceorder.mapper.ServiceOrderMapper;
import com.bolingcavalry.crm.summaryorder.mapper.ServiceSummaryOrderMapper;
import com.bolingcavalry.crm.summaryorder.service.ServiceSummaryOrderService;
import com.bolingcavalry.crm.taskorder.mapper.ConfirmationMapper;
import com.bolingcavalry.crm.taskorder.mapper.ReplacementPartMapper;
import com.bolingcavalry.crm.taskorder.mapper.TaskorderMapper;
import com.bolingcavalry.crm.utils.AUtils;
import com.dto.ReplacementPartDTO;
import com.dto.ServiceSummaryOrderDTO;
import com.entity.message.Message;
import com.entity.receiver.Receiver;
import com.entity.recyclebin.RecycleBinOrder;
import com.entity.summaryorder.ServiceSummaryOrder;
import com.entity.taskorder.ReplacementPart;
import com.vo.ReplacementPartVO;
import com.vo.ServiceSummaryOrderVO;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.bolingcavalry.crm.summaryorder.service.impl.TableParser.extractReplacementDetails;
import static com.bolingcavalry.crm.utils.AUtils.*;



@Service(Status.SUMMARY_ORDER)
public class ServiceSummaryOrderServiceImpl implements ServiceSummaryOrderService, OrderRestoreService {
    @Autowired
    private MinioService minioService;
    @Autowired
    private ServiceSummaryOrderMapper serviceSummaryOrderMapper;
    @Autowired
    private AUtils aUtils;
    @Autowired
    private RecyclebinMapper recyclebinMapper;
    @Autowired
    private ReplacementPartMapper replacementPartMapper;
    @Autowired
    private ReceiverMapper receiverMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private TaskorderMapper taskorderMapper;
    @Autowired
    private ServiceOrderMapper serviceOrderMapper;
    @Autowired
    private ConfirmationMapper confirmationMapper;
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Override
    public IPage<ServiceSummaryOrderVO> getByPage(Integer pageNum,
                                                  Integer pageSize,
                                                  String serviceNumber,
                                                  String customerCompany,
                                                  String salesManager,
                                                  String startDate,
                                                  String endDate) {

        // 处理分页参数
        Page<ServiceSummaryOrderVO> page;
        if (pageSize == null) {
            // 查询全部数据，使用足够大的页面大小
            page = new Page<>(1, 100000);
        } else {
            // 正常分页
            page = new Page<>(pageNum, pageSize);
        }

        IPage<ServiceSummaryOrderVO> resultPage = serviceSummaryOrderMapper.getBypage(page, serviceNumber, customerCompany, salesManager, startDate, endDate);

        List<ServiceSummaryOrderVO> voList = resultPage.getRecords();

        // 缓存 serviceNumber -> taskId，避免重复调用 aUtils
        Map<String, Long> serviceNumberToTaskIdMap = new HashMap<>();

        if (!voList.isEmpty()) {
            for (ServiceSummaryOrderVO vo : voList) {
                String currentServiceNumber = vo.getServiceNumber();

                // 从缓存中获取 taskId
                Long taskOrderId = serviceNumberToTaskIdMap.get(currentServiceNumber);

                // 如果缓存中没有，调用工具类获取并缓存
                if (taskOrderId == null && StringUtils.isNotBlank(currentServiceNumber)) {
                    taskOrderId = aUtils.getTaskOrderIdByServiceNumber(currentServiceNumber);
                    serviceNumberToTaskIdMap.put(currentServiceNumber, taskOrderId); // 写入缓存
                }

                if (taskOrderId != null) {
                    // 查询替换件列表
                    LambdaQueryWrapper<ReplacementPart> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(ReplacementPart::getTaskOrderId, taskOrderId)
                            .eq(ReplacementPart::getStatus, "2");

                    List<ReplacementPart> replacementPartList = replacementPartMapper.selectList(wrapper);

                    List<ReplacementPartVO> replacementPartVOList = new ArrayList<>();
                    if (replacementPartList != null && !replacementPartList.isEmpty()) {
                        for (ReplacementPart part : replacementPartList) {
                            ReplacementPartVO voItem = new ReplacementPartVO();
                            BeanUtils.copyProperties(part, voItem); // 注意参数顺序
                            replacementPartVOList.add(voItem);
                        }
                    }

                    vo.setReplacementPartList(replacementPartVOList);
                } else {
                    vo.setReplacementPartList(Collections.emptyList());
                }
            }
        }

        // 如果是查询全部，调整分页信息
        if (pageSize == null) {
            resultPage.setPages(1);
            resultPage.setCurrent(1);
            resultPage.setSize(resultPage.getTotal());
        }

        return resultPage;
    }


    /**
     * get查询单个服务总结单
     * @param id
     * @return
     */
    @Override
    public ServiceSummaryOrderVO getById(Long id) {
        ServiceSummaryOrder serviceSummaryOrder = serviceSummaryOrderMapper.selectById(id);
        ServiceSummaryOrderVO serviceSummaryOrderVO = new ServiceSummaryOrderVO();
        BeanUtils.copyProperties(serviceSummaryOrder, serviceSummaryOrderVO);
        Long customerCompanyId = serviceSummaryOrder.getCustomerCompanyId();
        Long customerContactsId = serviceSummaryOrder.getCustomerContactsId();
        Long salesManagerId = serviceSummaryOrder.getSalesManagerId();
        Long serviceImplementerId = serviceSummaryOrder.getServiceImplementerId();
        String customerCompanyName = aUtils.getCustomerCompanyNameById(customerCompanyId);
        //对vo设置四个id查询出来的name
        serviceSummaryOrderVO.setCustomerCompanyName(customerCompanyName);
        String contactPerson = aUtils.getContactPersonById(customerContactsId);
        serviceSummaryOrderVO.setCustomerContactsName(contactPerson);
        String salesManagerName = aUtils.getUserNickNameByUserId(salesManagerId);
        serviceSummaryOrderVO.setSalesManagerName(salesManagerName);
        String serviceImplementerName = aUtils.getUserNickNameByUserId(serviceImplementerId);
        serviceSummaryOrderVO.setServiceImplementerName(serviceImplementerName);

        //根据服务单id查询对应的更换零件表
        List<ReplacementPartVO> replacementPartVO = new ArrayList<>();
        LambdaQueryWrapper<ReplacementPart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReplacementPart::getTaskOrderId, serviceSummaryOrder.getTaskId())
                .eq(ReplacementPart::getStatus, "2");
        List<ReplacementPart> replacementPartList = replacementPartMapper.selectList(wrapper);
        if(replacementPartList!=null){
            for (ReplacementPart replacementPart : replacementPartList) {
                ReplacementPartVO partVO = new ReplacementPartVO();
                BeanUtils.copyProperties(replacementPart, partVO);
                replacementPartVO.add(partVO);
            }
        }
        //赋值中间表的内容到vo中
        serviceSummaryOrderVO.setReplacementPartList(replacementPartVO);
        return serviceSummaryOrderVO;
    }

    /**
     * 根据服务单号查询服务总结单
     * @param orderNumber
     * @return
     */
    @Override
    public ServiceSummaryOrderVO getByServiceNumber(String orderNumber) {
        LambdaQueryWrapper<ServiceSummaryOrder> wp = new LambdaQueryWrapper<>();
                        wp.eq(ServiceSummaryOrder::getServiceNumber, orderNumber)
                                .eq(ServiceSummaryOrder::getIsDeleted, 1);
        ServiceSummaryOrder serviceSummaryOrder = serviceSummaryOrderMapper.selectOne(wp);
        if(serviceSummaryOrder==null){
            return null;
        }
        ServiceSummaryOrderVO serviceSummaryOrderVO = new ServiceSummaryOrderVO();
        BeanUtils.copyProperties(serviceSummaryOrder, serviceSummaryOrderVO);
        Long customerCompanyId = serviceSummaryOrder.getCustomerCompanyId();
        Long customerContactsId = serviceSummaryOrder.getCustomerContactsId();
        Long salesManagerId = serviceSummaryOrder.getSalesManagerId();
        // 获取标准 yyyy-MM-dd 格式
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if(serviceSummaryOrder.getCompletionDate()!=null){
            String completionDate = serviceSummaryOrder.getCompletionDate().format(dateFormatter);
            serviceSummaryOrderVO.setCompletionDate(completionDate);
        }
        if(customerCompanyId!=null){
            String customerCompanyName = aUtils.getCustomerCompanyNameById(customerCompanyId);
            //对vo设置四个id查询出来的name
            serviceSummaryOrderVO.setCustomerCompanyName(customerCompanyName);
        }
        if(customerContactsId!=null){
            String contactPerson = aUtils.getContactPersonById(customerContactsId);
            serviceSummaryOrderVO.setCustomerContactsName(contactPerson);
        }
        if(salesManagerId!=null){
            String salesManagerName = aUtils.getUserNickNameByUserId(salesManagerId);
            serviceSummaryOrderVO.setSalesManagerName(salesManagerName);
        }
        //服务实施人，也就是任务接受人需要去中间表中获取，根据售后编号去receiver中获取
        //根据售后单号获取接收人名称（中间表查询）
        LambdaQueryWrapper<Receiver> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Receiver::getOrderNumber, serviceSummaryOrder.getServiceNumber());
        List<Receiver> receivers = receiverMapper.selectList(queryWrapper);
        List<String> receiverName = new ArrayList<>();
        for (Receiver receiver : receivers) {
            //根据用户ID获取名称
            String userNameByUserId = aUtils.getUserNickNameByUserId(receiver.getUserId());
            receiverName.add(userNameByUserId);
        }
        //设置服务实施人列表
        serviceSummaryOrderVO.setServiceImplementerNameList(receiverName);
        //根据服务单id查询对应的更换零件表
        List<ReplacementPartVO> replacementPartVO = new ArrayList<>();
        List<ReplacementPart> replacementPartList = replacementPartMapper.selectListByTaskOrderId(serviceSummaryOrder.getTaskId());
        if(replacementPartList!=null){
            double total = 0;
            for (ReplacementPart replacementPart : replacementPartList) {
                ReplacementPartVO partVO = new ReplacementPartVO();
                BeanUtils.copyProperties(replacementPart, partVO);
                replacementPartVO.add(partVO);
                //replacementPart.getQuantity()转为数字
                if(replacementPart.getQuantity()!=null && replacementPart.getPrice()!=null){
                    double v = Double.parseDouble(replacementPart.getQuantity());
                    total =total+replacementPart.getPrice() * v;
                }
            }
            serviceSummaryOrderVO.setTotal(total);
        }
        //赋值中间表的内容到vo中
        serviceSummaryOrderVO.setReplacementPartList(replacementPartVO);
        return serviceSummaryOrderVO;
    }

    /**
     * 新增服务总结单
     * 前端暂存 保存按钮分别对应status的editing 和 confirmed
     * @param order
     */
    @Override
    @Transactional
    public ResponseResult save(ServiceSummaryOrderDTO order) {
        ServiceSummaryOrder serviceSummaryOrder = new ServiceSummaryOrder();
        if(order==null){
            return ResponseResult.error("参数为空");
        }
        LambdaQueryWrapper<ServiceSummaryOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ServiceSummaryOrder::getServiceNumber, order.getServiceNumber())
                .eq(ServiceSummaryOrder::getIsDeleted, 1);
                if(serviceSummaryOrderMapper.selectOne(wrapper)!=null){
                    return ResponseResult.error("服务单号已存在，请勿重复添加");
                }
        BeanUtils.copyProperties(order, serviceSummaryOrder);
        //根据公司名称 联系人名称 业务经理名称 服务实施人名称查询出对应的id填入实体类表中
        if(order.getCustomerCompanyName()!=null)
            serviceSummaryOrder.setCustomerCompanyId(aUtils.getCustomerCompanyId(order.getCustomerCompanyName()));
        if(order.getCustomerContactsName()!=null && order.getCustomerCompanyName()!=null)
            serviceSummaryOrder.setCustomerContactsId(aUtils.getcontactPersonId(order.getCustomerContactsName(),order.getCustomerCompanyName()));
        if(order.getSalesManagerName()!=null)
            serviceSummaryOrder.setSalesManagerId(aUtils.getUserIdByNickName(order.getSalesManagerName()));
        if(order.getServiceImplementerName()!=null)
            serviceSummaryOrder.setServiceImplementerId(aUtils.getUserIdByNickName(order.getServiceImplementerName()));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.M.d");
        // 解析成 LocalDate
        if(order.getCompletionDate()!=null){
            LocalDate localDate = LocalDate.parse(order.getCompletionDate(), formatter);
            serviceSummaryOrder.setCompletionDate(localDate);
        }
        //根据服务单号查询任务单id
        Long id = aUtils.getTaskOrderIdByServiceNumber(order.getServiceNumber());
        serviceSummaryOrder.setTaskId(id);
        serviceSummaryOrder.setCreatedBy(SecurityUtils.getCurrentUsername());
        serviceSummaryOrder.setCreateTime(LocalDateTime.now());
        serviceSummaryOrderMapper.insert(serviceSummaryOrder);
        //根据服务id查询产品现场安装信息表id
        Long productInstallInfoId = aUtils.getProductInstallInfoIdByTaskOrderId(id);
        //插入中间表数据
        if(order.getReplacementPartList()!=null){
            for (ReplacementPartDTO replacementPartDTO : order.getReplacementPartList()) {
                if(replacementPartDTO.getPartName()== null){
                    continue;
                }
                ReplacementPart replacementPart = new ReplacementPart();
                BeanUtils.copyProperties(replacementPartDTO, replacementPart);
                replacementPart.setTaskOrderId(id);
                replacementPart.setProductInstallInfoId(productInstallInfoId);
                replacementPart.setStatus("2");
                replacementPart.setCreatedTime(LocalDateTime.now());
                replacementPart.setCreatedBy(SecurityUtils.getCurrentUsername());
                replacementPartMapper.insert(replacementPart);
            }
        }
        aUtils.updateServiceOrderUpdateTime(order.getServiceNumber());
        return ResponseResult.success("保存成功");
    }

    /**
     * 更新服务总结单
     * @param order
     */
    @Override
    @Transactional
    public ResponseResult update(ServiceSummaryOrderDTO order) {
        ServiceSummaryOrder serviceSummaryOrder = serviceSummaryOrderMapper.selectById(order.getId());
        if (serviceSummaryOrder == null) {
            return ResponseResult.error("找不到要更新的服务单");
        }
        //完结状态不允许编辑
        if(serviceSummaryOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_COMPLETED_TO_BE_REVIEWED)||serviceSummaryOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_COMPLETED)||serviceSummaryOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_ARCHIVED)){
            return ResponseResult.error("当前状态不允许编辑");
        }
        BeanUtils.copyProperties(order, serviceSummaryOrder);
        //根据公司名称 联系人名称 业务经理名称 服务实施人名称查询出对应的id填入实体类表中
        if(StringUtils.isNotBlank(order.getCustomerCompanyName()))
            serviceSummaryOrder.setCustomerCompanyId(aUtils.getCustomerCompanyId(order.getCustomerCompanyName()));
        if(StringUtils.isNotBlank(order.getCustomerContactsName())&&StringUtils.isNotBlank(order.getCustomerCompanyName()))
            serviceSummaryOrder.setCustomerContactsId(aUtils.getcontactPersonId(order.getCustomerContactsName(),order.getCustomerCompanyName()));
        if(StringUtils.isNotBlank(order.getSalesManagerName()))
            serviceSummaryOrder.setSalesManagerId(aUtils.getUserIdByNickName(order.getSalesManagerName()));
        if(StringUtils.isNotBlank(order.getServiceImplementerName()))
            serviceSummaryOrder.setServiceImplementerId(aUtils.getUserIdByNickName(order.getServiceImplementerName()));
        if (StringUtils.isNotBlank(order.getCompletionDate())) {
            // 增加对 "yyyy-MM-dd" 格式的解析支持
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(order.getCompletionDate(), formatter);
            serviceSummaryOrder.setCompletionDate(localDate);
        }
        serviceSummaryOrderMapper.updateById(serviceSummaryOrder);
        //根据服务单号查询任务单id
        Long id = aUtils.getTaskOrderIdByServiceNumber(order.getServiceNumber());
        //根据服务id查询产品现场安装信息表id
        Long productInstallInfoId = aUtils.getProductInstallInfoIdByTaskOrderId(id);
        //插入中间表数据
        if(order.getReplacementPartList()!=null){
            //删除原有的 中间表数据
            replacementPartMapper.deleteByTaskOrderId(id);
            for (ReplacementPartDTO replacementPartDTO : order.getReplacementPartList()) {
                ReplacementPart replacementPart = new ReplacementPart();
                BeanUtils.copyProperties(replacementPartDTO, replacementPart);
                replacementPart.setTaskOrderId(id);
                replacementPart.setProductInstallInfoId(productInstallInfoId);
                replacementPart.setStatus("2");
                replacementPartMapper.insert(replacementPart);
            }
        }
        aUtils.updateServiceOrderUpdateTime(order.getServiceNumber());
        return ResponseResult.success("更新成功");
    }

    /**
     * 批量删除服务总结单存入回收站
     * @param ids
     */
    @Override
    @Transactional
    public void batchDelete(String[] ids) {
        if (ids == null || ids.length == 0) {
            throw new IllegalArgumentException("删除ID列表不能为空");
        }
        //创建回收站实体类，存入回收站
        RecycleBinOrder recycleBin = new RecycleBinOrder();
        recycleBin.setDeletedBy(SecurityUtils.getCurrentUsername());
        recycleBin.setOrderType(Status.SUMMARY_ORDER);
        recycleBin.setDeleteTime(LocalDateTime.now());
        for (String id : ids) {
            ServiceSummaryOrder serviceSummaryOrder = serviceSummaryOrderMapper.selectById(id);
            if(serviceSummaryOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_COMPLETED)||serviceSummaryOrder.getStatus().equals(Status.SERVICE_ORDER_STATUS_ARCHIVED)){
                throw new RuntimeException("该服务单当前状态，不能删除");
            }
            recycleBin.setOrderId(serviceSummaryOrder.getId());
            recycleBin.setCustomerName(aUtils.getCustomerCompanyNameById(serviceSummaryOrder.getCustomerCompanyId()));
            recycleBin.setOrderNumber(serviceSummaryOrder.getServiceNumber());
            recyclebinMapper.insert(recycleBin);

            Long taskId = serviceSummaryOrder.getTaskId();
            LambdaQueryWrapper<ReplacementPart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ReplacementPart::getTaskOrderId, taskId)
                    .eq(ReplacementPart::getStatus, "2");
            //删除关联的中间表数据
            replacementPartMapper.delete(wrapper);
            //修改ifdeleted为0
            serviceSummaryOrder.setIsDeleted(0);
            LambdaUpdateWrapper<ServiceSummaryOrder> wrapper1 = new LambdaUpdateWrapper<>();
            wrapper1.eq(ServiceSummaryOrder::getId, id);
            serviceSummaryOrderMapper.update(serviceSummaryOrder, wrapper1);

            //修改总括表同步为已完结
            afterSalesMapper.updateStatusByOrderNumber(serviceSummaryOrder.getServiceNumber(), Status.SERVICE_ORDER_STATUS_TO_BE_SUMMARIZED);
            //设置任务表同步为已完结
            taskorderMapper.updateStatusByOrderNumber(serviceSummaryOrder.getServiceNumber(), Status.SERVICE_ORDER_STATUS_TO_BE_SUMMARIZED);
            //设置确认单同步为已完结
            confirmationMapper.updateStatusByOrderNumber(serviceSummaryOrder.getServiceNumber(), Status.SERVICE_ORDER_STATUS_TO_BE_SUMMARIZED);
            //设置通知单同步为已完结
            serviceOrderMapper.updateStatusByOrderNumber(serviceSummaryOrder.getServiceNumber(), Status.SERVICE_ORDER_STATUS_TO_BE_SUMMARIZED);

            //删除对应的发出去的消息
            LambdaQueryWrapper<Message> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(Message::getOrderNumber,serviceSummaryOrder.getServiceNumber())
                    .eq(Message::getBusinessType, Status.SUMMARY_ORDER);
            messageMapper.delete(wrapper2);
        }
    }


    /**
     * 工厂方法 恢复工单状态
     * @param orderId
     * @return
     */
    @Override
    public boolean restoreOrderById(Long orderId) {
        //设置isdelete为1 恢复数据
        ServiceSummaryOrder serviceSummaryOrder = new ServiceSummaryOrder();
        serviceSummaryOrder.setIsDeleted(1);
        return serviceSummaryOrderMapper.update(serviceSummaryOrder, new LambdaQueryWrapper<ServiceSummaryOrder>().eq(ServiceSummaryOrder::getId, orderId)) > 0;
    }

    /**
     * 彻底删除工单
     * @param orderId
     * @return
     */
    @Override
    public boolean deleteOrderById(Long orderId) {
        return serviceSummaryOrderMapper.deleteById(orderId) > 0;
    }


    /**
     * 根据图片更新服务总结单
     * @param image
     */
    @Override
    @Transactional
    public ServiceSummaryOrderVO updateByImage(MultipartFile image) throws Exception {
        //创建上传图片到minio获取图片的objectName
        String objectName = minioService.uploadFile(image);
        //根据图片objectName获取预签名url存入实体类中
        String presignedUrl = minioService.getPresignedUrl(objectName);
        //调用百度ai的接口，解析图片，获取表格内容以下方法通用
        if (image == null || image.isEmpty()) {
            throw new IllegalArgumentException("上传的图片不能为空");
        }
        // 获取文件字节流并转成 Base64 也可以通过图片的路径转为base64，（重载方法）
        String s1 =aUtils.getFileContentAsBase64(image, true);
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\123.png") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        //String content = getFileContentAsBase64("C:\\Users\\23234\\Desktop\\e96779f258fc4d2a54edd7e14dfb4de.jpg",true);
        RequestBody body = RequestBody.create(mediaType, "image="+s1);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/table?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String s = response.body().string();
        System.out.println(s);
        JSONObject jsonObject = new JSONObject(s);
        // 从 tables_result 中获取 body 数组
        JSONArray tablesResult = jsonObject.getJSONArray("tables_result");
        JSONObject firstTable = tablesResult.getJSONObject(0);
        JSONArray body1 = firstTable.getJSONArray("body");

        ServiceSummaryOrderVO serviceSummaryOrderVO = new ServiceSummaryOrderVO();
        //使用通用方法查询字段的值
        String serviceNumber = extractFieldValue(body1, "服务单号");
        serviceSummaryOrderVO.setServiceNumber(serviceNumber);
        //根据服务单号查询任务单id
        Long id = aUtils.getTaskOrderIdByServiceNumber(serviceNumber);
        String serviceImplementerName = extractFieldValue(body1, "服务实施人");
        serviceSummaryOrderVO.setServiceImplementerName(serviceImplementerName);
        String overDate = extractFieldValue(body1, "完成时间");
        serviceSummaryOrderVO.setCompletionDate(overDate);
        String customerCompanyName = extractFieldValue(body1, "客户名称");
        serviceSummaryOrderVO.setCustomerCompanyName(customerCompanyName);
        String customerContactsName = extractFieldValue(body1, "联系人");
        serviceSummaryOrderVO.setCustomerContactsName(customerContactsName);
        String salesManagerName = extractFieldValue(body1, "销售经理");
        serviceSummaryOrderVO.setSalesManagerName(salesManagerName);
        String serviceLocation = extractFieldValue(body1, "服务地点");
        serviceSummaryOrderVO.setServiceLocation(serviceLocation);
        String serviceDetail = extractFieldValue(body1, "工作明细");
        serviceSummaryOrderVO.setWorkDetails(serviceDetail);
        String sum  = extractFieldValue(body1, "合计");
        //设置图片的url
        serviceSummaryOrderVO.setImagesUrl(presignedUrl);
        //存入数据库
        //serviceSummaryOrderMapper.insert(serviceSummaryOrder);

        // 更换明细中的名称、规格、数量、单价
        // 调用提取方法
        List<ReplacementPartVO> replacementDetails = new ArrayList<>();
        List<Map<String, String>> replacementDetailsList = extractReplacementDetails(body1);
        for (Map<String, String> item : replacementDetailsList) {
            //存入更换零部件表实体类中
            ReplacementPartVO replacementPartVO = new ReplacementPartVO();
            replacementPartVO.setPartName(item.get("名称"));
            replacementPartVO.setSpecification(item.get("规格"));
            replacementPartVO.setQuantity(item.get("数量"));
            String price = item.get("单价（元）");
            if(!price.isEmpty()){
                replacementPartVO.setPrice(Double.parseDouble(price));
            }
            replacementDetails.add(replacementPartVO);
        }
        serviceSummaryOrderVO.setReplacementPartList(replacementDetails);
        return serviceSummaryOrderVO;
    }

    @Override
    public void updateStatus(Long id, String status) {
         serviceSummaryOrderMapper.updateStatus(id,status);
    }

    /**
     * 从 OCR 的 body 数组中提取指定字段名后面的值
     * @param body JSONArray 类型的 OCR 表格 body 数据
     * @param fieldName 要查找的字段名，如 "服务单号"、"工作明细" 等
     * @return 对应字段值，未找到或出错返回 null
     */
    public String extractFieldValue(JSONArray body, String fieldName) {
        for (int i = 0; i < body.length(); i++) {
            JSONObject currentCell = body.getJSONObject(i);
            String word = currentCell.optString("words", "").trim();

            if (fieldName.equals(word)) {
                // 确保不是最后一个单元格
                if (i + 1 < body.length()) {
                    JSONObject nextCell = body.getJSONObject(i + 1);
                    return nextCell.optString("words", "").trim();
                }
            }
        }
        return null;
    }


}